﻿using System;
using System.Web.UI.WebControls;
using Hematology.HmtMembership;
using Hematology.Tools;
using Hematology.Tools.Storage;
using Hematology.UserSite.Controls;
using NgoResource = Hematology.UserSite.App_GlobalResources.UserSite;

namespace Hematology.UserSite
{
	public partial class Profile : NgoPage
	{
		private EnumHelper.ProfileSection CurrentProfileSection
		{
			get
			{
				return ViewState["CurrentProfileSection"] != null
						   ? (EnumHelper.ProfileSection)Enum.Parse(typeof(EnumHelper.ProfileSection), ViewState["CurrentProfileSection"].ToString())
						   : EnumHelper.ProfileSection.General;
			}
			set { ViewState["CurrentProfileSection"] = value; }
		}

		private void FillViewStateVariables()
		{
			string pageSection = Request.QueryString["view"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.ProfileSection)), pageSection) > -1)
			{
				CurrentProfileSection =
					(EnumHelper.ProfileSection)Enum.Parse(typeof(EnumHelper.ProfileSection), pageSection);
			}
		}

		private void FillPage()
		{
			FillViewStateVariables();

			switch (CurrentProfileSection)
			{
				case EnumHelper.ProfileSection.ChangePassword:
					mvProfile.ActiveViewIndex = 1;
					lblTitle.Text = NgoResource.resChangePassword;
					break;
				case EnumHelper.ProfileSection.AddLinks:
					mvProfile.ActiveViewIndex = 2;
					lblTitle.Text = NgoResource.resAddArticleLinks;
					break;
				default:
					mvProfile.ActiveViewIndex = 0;
					lblTitle.Text = NgoResource.resCommonInformation;
					break;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (Page.IsPostBack)
				return;

			if (!MembershipHelper.MembershipService.IsAuthorizedRequest)
			{
				Response.Redirect("/");
			}
			else
			{
				FillPage();
			}
		}

		protected void btnProfileSaveGeneralChanges_Click(object sender, EventArgs e)
		{
			SessionHelper.ActiveUser.Update();
		}

		protected void btnChangePassword_Click(object sender, EventArgs e)
		{
			string sNewPassword = txtNewPassword.Text;
			string sRepeatNewPassword = txtRepeatNewPassword.Text;

			if (String.Compare(sNewPassword, sRepeatNewPassword, false) == 0)
			{
				string sOldPassword = txtOldPassword.Text;
				MembershipHelper.MembershipService.ChangePassword(SessionHelper.ActiveUser.BaseInfo.Email,
																  sOldPassword,
																  sNewPassword);
			}
		}

		protected void validOldPassword_ServerValidate(object sender, ServerValidateEventArgs e)
		{
			e.IsValid = MembershipHelper.MembershipService.ValidateUser(SessionHelper.ActiveUser.BaseInfo.Email, e.Value);
		}
	}
}